<?php
/**
 * Copyright 2013 Marek Kaszewski
 *
 * This file is part of the JHUB1 Online Community Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Jhub1_Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Jhub1_Common\Entity\BO\UsersBO;
use Jhub1_Admin\Form\Registration;
use Jhub1_Admin\Form\PasswordReminder;
use Jhub1_Admin\Model\FormFilter\RegistrationFilter;
use Jhub1_Admin\Model\FormFilter\PasswordReminderFilter;
use Jhub1_Common\Model\Mailer;
use Zend\Session\Container;
use Jhub1_Common\Model\SettingsObjects\DateTimeObject;
#use Application\Model\SettingsObjects\UserLocalizationObject;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        #  $ulo = new UserLocalizationObject();
        #   $ulo->fromJSON($ulo->toJSON());
     //   $dto = new DateTimeObject();
      //  echo $dto->toTimestamp();
      #  $dto->fromTimestamp('1382309217');
     #   var_dump($dto);
    //    die;
   //     return new ViewModel();
        $view = new ViewModel();
     //   $view->setTerminal(true);
        return $view;
    }

    public function registerAction()
    {
        $form = new Registration();
        /**
         * @TODO check first if ID is unique!!!
         */
        $request = $this->getRequest();
        if ($request->isPost()) {
            $regFilter = new RegistrationFilter();
            $form->setInputFilter($regFilter->getInputFilter());
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $userBO = new UsersBO($this->getServiceLocator());
                $formData = $form->getData();
                $regFilter->exchangeArray($form->getData());
                $existUserPO = $userBO->getUserByEmail($formData['email']);
                if (null == $existUserPO) {
                    $newUserPO = $userBO->insertUser($regFilter->getFormData());
                    $email = new Mailer();
                    /**
                     * @TODO if return false - problem with sending email message
                     */
                    $succeed = $email->sendActivationCode($newUserPO);
                    if($succeed) {
                        return array('succeed' => $succeed,
                            'statusMessage' => 'theActivationCodeEmailHasBeenSent',
                        );
                    } else {
                        return array('succeed' => $succeed,
                            'statusMessage' => 'errorWithSendingActivationCodeEmail',
                        );
                    }
                } else {
                    return array('error' => true,
                        'formData' => $form->getData(),
                        'formMessages' => $form->getMessages(),
                        'message' => 'userExists',
                    );
                }

                // Successful login Redirect to list of campaign
                return $this->redirect()->toRoute('activate');
            } else {
                return array('error' => true,
                    'formData' => $form->getData(),
                    'formMessages' => $form->getMessages()
                );
            }
        }
        return array('form' => $form);
    }

    public function activateaccountAction()
    {
        $code = $this->getEvent()->getRouteMatch()->getParam('code');
        if (!empty($code)) {
            $userBO = new UsersBO($this->getServiceLocator());
            $userPO = $userBO->activateUserFromEmail($code);
            if (null != $userPO) {
                $session_user = new Container('user');
                $session_user->offsetSet('userobject', $userPO);
                $session_user->offsetSet('justActivated', true);
                return $this->redirect()->toRoute('welcome');
            }
        }
        return $this->redirect()->toRoute('home');
    }

    public function resendactivationemailAction()
    {
        $code = $this->getEvent()->getRouteMatch()->getParam('code');
        if (!empty($code)) {
            $userBO = new UsersBO($this->getServiceLocator());
            $userPO = $userBO->getUserByResendCode($code);
            if (null != $userPO) {
                $email = new Mailer();
                /**
                 * @TODO if return false - problem with sending email message cover $succeed cases
                 */
                $succeed = $email->sendActivationCode($userPO);
                return $this->redirect()->toRoute('authenticate');
            }
        }
        return $this->redirect()->toRoute('home');
    }

    public function passwordreminderAction()
    {
        $form = new PasswordReminder();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $prFilter = new PasswordReminderFilter();
            $form->setInputFilter($prFilter->getInputFilter());
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $formData = $form->getData();
                $userBO = new UsersBO($this->getServiceLocator());
                $userPO = $userBO->getUserByEmail($formData['email']);
                if(null != $userPO) {
                    $email = new Mailer();
                    /**
                     * @TODO if return false - problem with sending email message
                     */
                    $succeed = $email->sendPasswordReminder($userPO);
                    if($succeed) {
                        return array('succeed' => $succeed,
                                     'statusMessage' => 'The Password Reminder Email Has Been Sent',
                        );
                    } else {
                        return array('succeed' => $succeed,
                            'statusMessage' => 'There is a problem with sending password reset email. Please try later.',
                        );
                    }

                } else {
                    return array('error' => true,
                        'formData' => $form->getData(),
                        'formMessages' => $form->getMessages(),
                        'message' => 'userNotFound',
                    );
                }
            } else {
                return array('error' => true,
                    'formData' => $form->getData(),
                    'formMessages' => $form->getMessages()
                );
            }
        }
        return new ViewModel();
    }

    public function activateAction()
    {

        /*        $session_user = new Container('user');
                $session_user_errors = new Container('usererrors');
                $session_user_shares = new Container('usershares');
                $email = $session_user->offsetGet('email');
        // Setting value in session: ( set value from namespace )

                $session_user->offsetSet('username', 'abcd');
                $session_user->getManager()->getStorage()->clear('user');

                $container = new Container('namespace');
                $container->set   item = 'foo';*/

        return new ViewModel();
    }

}
